package com.example.seataxa.business.service.impl;

import com.example.seataxa.business.controller.TestData;
import com.example.seataxa.business.feign.OrderFeignClient;
import com.example.seataxa.business.feign.StockFeignClient;
import com.example.seataxa.business.service.BusinessService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 季舟
 * @Date 2024-09-14 15:40
 */
@Service
public class BusinessServiceImpl implements BusinessService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private StockFeignClient stockFeignClient;
    @Resource
    private OrderFeignClient orderFeignClient;

    /**
     * 用户订购商品
     *
     * @param userId        用户ID
     * @param commodityCode 商品编号
     * @param orderCount    订购数量
     * @param forceRollback forceRollback
     */
    @Override
    @GlobalTransactional
    public void purchase(String userId, String commodityCode, int orderCount, boolean forceRollback) {
        System.out.println("开始下单，用户：" + userId + " 商品：" + commodityCode + " 数量：" + orderCount);
        stockFeignClient.deduct(commodityCode, orderCount);
        orderFeignClient.create(userId, commodityCode, orderCount);
        if (forceRollback) {
            System.out.println("Force rollback: "+commodityCode+" "+orderCount);
            throw new RuntimeException("Force rollback ... ");
        }
    }

    //@PostConstruct
    public void initData() {
        jdbcTemplate.update("delete from account_tbl");
        jdbcTemplate.update("delete from order_tbl");
        jdbcTemplate.update("delete from stock_tbl");
        jdbcTemplate.update("insert into account_tbl(user_id,money) values('" + TestData.USER_ID + "','10000') ");
        jdbcTemplate.update("insert into stock_tbl(commodity_code,count) values('" + TestData.COMMODITY_CODE + "','100') ");
    }
}
